home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / gzip.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  14KB  |  515 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """Functions that read and write gzipped files.
  5.  
  6. The user of the file doesn't have to worry about the compression,
  7. but random access is not allowed."""
  8. import struct
  9. import sys
  10. import time
  11. import zlib
  12. import __builtin__
  13. __all__ = [
  14.     'GzipFile',
  15.     'open']
  16. (FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT) = (1, 2, 4, 8, 16)
  17. (READ, WRITE) = (1, 2)
  18.  
  19. def write32u(output, value):
  20.     output.write(struct.pack('<L', value))
  21.  
  22.  
  23. def read32(input):
  24.     return struct.unpack('<I', input.read(4))[0]
  25.  
  26.  
  27. def open(filename, mode = 'rb', compresslevel = 9):
  28.     """Shorthand for GzipFile(filename, mode, compresslevel).
  29.  
  30.     The filename argument is required; mode defaults to 'rb'
  31.     and compresslevel defaults to 9.
  32.  
  33.     """
  34.     return GzipFile(filename, mode, compresslevel)
  35.  
  36.  
  37. class GzipFile:
  38.     '''The GzipFile class simulates most of the methods of a file object with
  39.     the exception of the readinto() and truncate() methods.
  40.  
  41.     '''
  42.     myfileobj = None
  43.     max_read_chunk = 10485760
  44.     
  45.     def __init__(self, filename = None, mode = None, compresslevel = 9, fileobj = None):
  46.         """Constructor for the GzipFile class.
  47.  
  48.         At least one of fileobj and filename must be given a
  49.         non-trivial value.
  50.  
  51.         The new class instance is based on fileobj, which can be a regular
  52.         file, a StringIO object, or any other object which simulates a file.
  53.         It defaults to None, in which case filename is opened to provide
  54.         a file object.
  55.  
  56.         When fileobj is not None, the filename argument is only used to be
  57.         included in the gzip file header, which may includes the original
  58.         filename of the uncompressed file.  It defaults to the filename of
  59.         fileobj, if discernible; otherwise, it defaults to the empty string,
  60.         and in this case the original filename is not included in the header.
  61.  
  62.         The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb',
  63.         depending on whether the file will be read or written.  The default
  64.         is the mode of fileobj if discernible; otherwise, the default is 'rb'.
  65.         Be aware that only the 'rb', 'ab', and 'wb' values should be used
  66.         for cross-platform portability.
  67.  
  68.         The compresslevel argument is an integer from 1 to 9 controlling the
  69.         level of compression; 1 is fastest and produces the least compression,
  70.         and 9 is slowest and produces the most compression.  The default is 9.
  71.  
  72.         """
  73.         if mode and 'b' not in mode:
  74.             mode += 'b'
  75.         
  76.         if fileobj is None:
  77.             if not mode:
  78.                 pass
  79.             fileobj = self.myfileobj = __builtin__.open(filename, 'rb')
  80.         
  81.         if filename is None:
  82.             if hasattr(fileobj, 'name'):
  83.                 filename = fileobj.name
  84.             else:
  85.                 filename = ''
  86.         
  87.         if mode is None:
  88.             if hasattr(fileobj, 'mode'):
  89.                 mode = fileobj.mode
  90.             else:
  91.                 mode = 'rb'
  92.         
  93.         if mode[0:1] == 'r':
  94.             self.mode = READ
  95.             self._new_member = True
  96.             self.extrabuf = ''
  97.             self.extrasize = 0
  98.             self.name = filename
  99.             self.min_readsize = 100
  100.         elif mode[0:1] == 'w' or mode[0:1] == 'a':
  101.             self.mode = WRITE
  102.             self._init_write(filename)
  103.             self.compress = zlib.compressobj(compresslevel, zlib.DEFLATED, -(zlib.MAX_WBITS), zlib.DEF_MEM_LEVEL, 0)
  104.         else:
  105.             raise IOError, 'Mode ' + mode + ' not supported'
  106.         self.fileobj = mode[0:1] == 'a'
  107.         self.offset = 0
  108.         if self.mode == WRITE:
  109.             self._write_gzip_header()
  110.         
  111.  
  112.     
  113.     def filename(self):
  114.         import warnings as warnings
  115.         warnings.warn('use the name attribute', DeprecationWarning, 2)
  116.         if self.mode == WRITE and self.name[-3:] != '.gz':
  117.             return self.name + '.gz'
  118.         return self.name
  119.  
  120.     filename = property(filename)
  121.     
  122.     def __repr__(self):
  123.         s = repr(self.fileobj)
  124.         return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
  125.  
  126.     
  127.     def _init_write(self, filename):
  128.         self.name = filename
  129.         self.crc = zlib.crc32('') & 0xFFFFFFFFL
  130.         self.size = 0
  131.         self.writebuf = []
  132.         self.bufsize = 0
  133.  
  134.     
  135.     def _write_gzip_header(self):
  136.         self.fileobj.write('\x1f\x8b')
  137.         self.fileobj.write('\x08')
  138.         fname = self.name
  139.         if fname.endswith('.gz'):
  140.             fname = fname[:-3]
  141.         
  142.         flags = 0
  143.         if fname:
  144.             flags = FNAME
  145.         
  146.         self.fileobj.write(chr(flags))
  147.         write32u(self.fileobj, long(time.time()))
  148.         self.fileobj.write('\x02')
  149.         self.fileobj.write('\xff')
  150.         if fname:
  151.             self.fileobj.write(fname + '\x00')
  152.         
  153.  
  154.     
  155.     def _init_read(self):
  156.         self.crc = zlib.crc32('') & 0xFFFFFFFFL
  157.         self.size = 0
  158.  
  159.     
  160.     def _read_gzip_header(self):
  161.         magic = self.fileobj.read(2)
  162.         if magic != '\x1f\x8b':
  163.             raise IOError, 'Not a gzipped file'
  164.         magic != '\x1f\x8b'
  165.         method = ord(self.fileobj.read(1))
  166.         if method != 8:
  167.             raise IOError, 'Unknown compression method'
  168.         method != 8
  169.         flag = ord(self.fileobj.read(1))
  170.         self.fileobj.read(6)
  171.         if flag & FEXTRA:
  172.             xlen = ord(self.fileobj.read(1))
  173.             xlen = xlen + 256 * ord(self.fileobj.read(1))
  174.             self.fileobj.read(xlen)
  175.         
  176.         if flag & FNAME:
  177.             while True:
  178.                 s = self.fileobj.read(1)
  179.                 if not s or s == '\x00':
  180.                     break
  181.                     continue
  182.         
  183.         if flag & FCOMMENT:
  184.             while True:
  185.                 s = self.fileobj.read(1)
  186.                 if not s or s == '\x00':
  187.                     break
  188.                     continue
  189.         
  190.         if flag & FHCRC:
  191.             self.fileobj.read(2)
  192.         
  193.  
  194.     
  195.     def write(self, data):
  196.         if self.mode != WRITE:
  197.             import errno as errno
  198.             raise IOError(errno.EBADF, 'write() on read-only GzipFile object')
  199.         self.mode != WRITE
  200.         if self.fileobj is None:
  201.             raise ValueError, 'write() on closed GzipFile object'
  202.         self.fileobj is None
  203.         if len(data) > 0:
  204.             self.size = self.size + len(data)
  205.             self.crc = zlib.crc32(data, self.crc) & 0xFFFFFFFFL
  206.             self.fileobj.write(self.compress.compress(data))
  207.             self.offset += len(data)
  208.         
  209.  
  210.     
  211.     def read(self, size = -1):
  212.         if self.mode != READ:
  213.             import errno
  214.             raise IOError(errno.EBADF, 'read() on write-only GzipFile object')
  215.         self.mode != READ
  216.         if self.extrasize <= 0 and self.fileobj is None:
  217.             return ''
  218.         readsize = 1024
  219.         if size < 0:
  220.             
  221.             try:
  222.                 while True:
  223.                     self._read(readsize)
  224.                     readsize = min(self.max_read_chunk, readsize * 2)
  225.                     continue
  226.                     self.fileobj is None
  227.             except EOFError:
  228.                 self.fileobj is None
  229.                 self.fileobj is None
  230.                 size = self.extrasize
  231.             except:
  232.                 self.fileobj is None<EXCEPTION MATCH>EOFError
  233.             
  234.  
  235.         self.fileobj is None
  236.         
  237.         try:
  238.             while size > self.extrasize:
  239.                 self._read(readsize)
  240.                 readsize = min(self.max_read_chunk, readsize * 2)
  241.                 continue
  242.                 self.fileobj is None
  243.         except EOFError:
  244.             self.fileobj is None
  245.             self.fileobj is None
  246.             if size > self.extrasize:
  247.                 size = self.extrasize
  248.             
  249.         except:
  250.             size > self.extrasize
  251.  
  252.         chunk = self.extrabuf[:size]
  253.         self.extrabuf = self.extrabuf[size:]
  254.         self.extrasize = self.extrasize - size
  255.         self.offset += size
  256.         return chunk
  257.  
  258.     
  259.     def _unread(self, buf):
  260.         self.extrabuf = buf + self.extrabuf
  261.         self.extrasize = len(buf) + self.extrasize
  262.         self.offset -= len(buf)
  263.  
  264.     
  265.     def _read(self, size = 1024):
  266.         if self.fileobj is None:
  267.             raise EOFError, 'Reached EOF'
  268.         self.fileobj is None
  269.         if self._new_member:
  270.             pos = self.fileobj.tell()
  271.             self.fileobj.seek(0, 2)
  272.             if pos == self.fileobj.tell():
  273.                 raise EOFError, 'Reached EOF'
  274.             pos == self.fileobj.tell()
  275.             self.fileobj.seek(pos)
  276.             self._init_read()
  277.             self._read_gzip_header()
  278.             self.decompress = zlib.decompressobj(-(zlib.MAX_WBITS))
  279.             self._new_member = False
  280.         
  281.         buf = self.fileobj.read(size)
  282.         if buf == '':
  283.             uncompress = self.decompress.flush()
  284.             self._read_eof()
  285.             self._add_read_data(uncompress)
  286.             raise EOFError, 'Reached EOF'
  287.         buf == ''
  288.         uncompress = self.decompress.decompress(buf)
  289.         self._add_read_data(uncompress)
  290.         if self.decompress.unused_data != '':
  291.             self.fileobj.seek(-len(self.decompress.unused_data) + 8, 1)
  292.             self._read_eof()
  293.             self._new_member = True
  294.         
  295.  
  296.     
  297.     def _add_read_data(self, data):
  298.         self.crc = zlib.crc32(data, self.crc) & 0xFFFFFFFFL
  299.         self.extrabuf = self.extrabuf + data
  300.         self.extrasize = self.extrasize + len(data)
  301.         self.size = self.size + len(data)
  302.  
  303.     
  304.     def _read_eof(self):
  305.         self.fileobj.seek(-8, 1)
  306.         crc32 = read32(self.fileobj)
  307.         isize = read32(self.fileobj)
  308.         if crc32 != self.crc:
  309.             raise IOError('CRC check failed %s != %s' % (hex(crc32), hex(self.crc)))
  310.         crc32 != self.crc
  311.         if isize != self.size & 0xFFFFFFFFL:
  312.             raise IOError, 'Incorrect length of data produced'
  313.         isize != self.size & 0xFFFFFFFFL
  314.  
  315.     
  316.     def close(self):
  317.         if self.fileobj is None:
  318.             return None
  319.         if self.mode == WRITE:
  320.             self.fileobj.write(self.compress.flush())
  321.             write32u(self.fileobj, self.crc)
  322.             write32u(self.fileobj, self.size & 0xFFFFFFFFL)
  323.             self.fileobj = None
  324.         elif self.mode == READ:
  325.             self.fileobj = None
  326.         
  327.         if self.myfileobj:
  328.             self.myfileobj.close()
  329.             self.myfileobj = None
  330.         
  331.  
  332.     
  333.     def __del__(self):
  334.         
  335.         try:
  336.             if self.myfileobj is None and self.fileobj is None:
  337.                 return None
  338.         except AttributeError:
  339.             return None
  340.  
  341.         self.close()
  342.  
  343.     
  344.     def flush(self, zlib_mode = zlib.Z_SYNC_FLUSH):
  345.         if self.mode == WRITE:
  346.             self.fileobj.write(self.compress.flush(zlib_mode))
  347.         
  348.         self.fileobj.flush()
  349.  
  350.     
  351.     def fileno(self):
  352.         """Invoke the underlying file object's fileno() method.
  353.  
  354.         This will raise AttributeError if the underlying file object
  355.         doesn't support fileno().
  356.         """
  357.         return self.fileobj.fileno()
  358.  
  359.     
  360.     def isatty(self):
  361.         return False
  362.  
  363.     
  364.     def tell(self):
  365.         return self.offset
  366.  
  367.     
  368.     def rewind(self):
  369.         '''Return the uncompressed stream file position indicator to the
  370.         beginning of the file'''
  371.         if self.mode != READ:
  372.             raise IOError("Can't rewind in write mode")
  373.         self.mode != READ
  374.         self.fileobj.seek(0)
  375.         self._new_member = True
  376.         self.extrabuf = ''
  377.         self.extrasize = 0
  378.         self.offset = 0
  379.  
  380.     
  381.     def seek(self, offset, whence = 0):
  382.         if whence:
  383.             if whence == 1:
  384.                 offset = self.offset + offset
  385.             else:
  386.                 raise ValueError('Seek from end not supported')
  387.         whence == 1
  388.         if self.mode == WRITE:
  389.             if offset < self.offset:
  390.                 raise IOError('Negative seek in write mode')
  391.             offset < self.offset
  392.             count = offset - self.offset
  393.             for i in range(count // 1024):
  394.                 self.write(1024 * '\x00')
  395.             
  396.             self.write((count % 1024) * '\x00')
  397.         elif self.mode == READ:
  398.             if offset < self.offset:
  399.                 self.rewind()
  400.             
  401.             count = offset - self.offset
  402.             for i in range(count // 1024):
  403.                 self.read(1024)
  404.             
  405.             self.read(count % 1024)
  406.         
  407.  
  408.     
  409.     def readline(self, size = -1):
  410.         if size < 0:
  411.             size = sys.maxint
  412.             readsize = self.min_readsize
  413.         else:
  414.             readsize = size
  415.         bufs = []
  416.         while size != 0:
  417.             c = self.read(readsize)
  418.             i = c.find('\n')
  419.             if (size <= i or i == -1) and len(c) > size:
  420.                 i = size - 1
  421.             
  422.             if i >= 0 or c == '':
  423.                 bufs.append(c[:i + 1])
  424.                 self._unread(c[i + 1:])
  425.                 break
  426.             
  427.             bufs.append(c)
  428.             size = size - len(c)
  429.             readsize = min(size, readsize * 2)
  430.         if readsize > self.min_readsize:
  431.             self.min_readsize = min(readsize, self.min_readsize * 2, 512)
  432.         
  433.         return ''.join(bufs)
  434.  
  435.     
  436.     def readlines(self, sizehint = 0):
  437.         if sizehint <= 0:
  438.             sizehint = sys.maxint
  439.         
  440.         L = []
  441.         while sizehint > 0:
  442.             line = self.readline()
  443.             if line == '':
  444.                 break
  445.             
  446.             L.append(line)
  447.             sizehint = sizehint - len(line)
  448.         return L
  449.  
  450.     
  451.     def writelines(self, L):
  452.         for line in L:
  453.             self.write(line)
  454.         
  455.  
  456.     
  457.     def __iter__(self):
  458.         return self
  459.  
  460.     
  461.     def next(self):
  462.         line = self.readline()
  463.         if line:
  464.             return line
  465.         raise StopIteration
  466.  
  467.  
  468.  
  469. def _test():
  470.     args = sys.argv[1:]
  471.     if args:
  472.         pass
  473.     decompress = args[0] == '-d'
  474.     if decompress:
  475.         args = args[1:]
  476.     
  477.     if not args:
  478.         args = [
  479.             '-']
  480.     
  481.     for arg in args:
  482.         if decompress:
  483.             if arg == '-':
  484.                 f = GzipFile(filename = '', mode = 'rb', fileobj = sys.stdin)
  485.                 g = sys.stdout
  486.             elif arg[-3:] != '.gz':
  487.                 print "filename doesn't end in .gz:", repr(arg)
  488.                 continue
  489.             
  490.             f = open(arg, 'rb')
  491.             g = __builtin__.open(arg[:-3], 'wb')
  492.         elif arg == '-':
  493.             f = sys.stdin
  494.             g = GzipFile(filename = '', mode = 'wb', fileobj = sys.stdout)
  495.         else:
  496.             f = __builtin__.open(arg, 'rb')
  497.             g = open(arg + '.gz', 'wb')
  498.         while True:
  499.             chunk = f.read(1024)
  500.             if not chunk:
  501.                 break
  502.             
  503.             g.write(chunk)
  504.         if g is not sys.stdout:
  505.             g.close()
  506.         
  507.         if f is not sys.stdin:
  508.             f.close()
  509.             continue
  510.     
  511.  
  512. if __name__ == '__main__':
  513.     _test()
  514.  
  515.